#!/bin/bash

set -e

NAMESPACE="qatest"
JOB_NAME="logseer-test"
YAML_FILE="{{data_dir}}/logseer-qatest/logseer/logseer_job_test.yml"
CONFIGMAP_TESTXML_FILE="{{data_dir}}/logseer-qatest/logseer/testng.xml"
CONFIGMAP_TESTXML_NAME="logseer-test-xml"


if [ -d {{data_dir}}/logseer-qatest/logseer/logs ];then
    mv {{data_dir}}/logseer-qatest/logseer/logs {{data_dir}}/logseer-qatest/logseer/logs-`date +%F-%H%M%S`
fi

if [ -d {{data_dir}}/logseer-qatest/logseer/test-output ];then
    mv {{data_dir}}/logseer-qatest/logseer/test-output  {{data_dir}}/logseer-qatest/logseer/test-output-`date +%F-%H%M%S`
fi

if [ ! -n "$(~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf get namespaces | grep $NAMESPACE)" ]; then
    ~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf create namespace qatest
fi

if [  -n "$(~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf get configmap -n $NAMESPACE | grep $CONFIGMAP_TESTXML_NAME)" ]; then
        ~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf delete configmap $CONFIGMAP_TESTXML_NAME -n $NAMESPACE
        ~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf create configmap $CONFIGMAP_TESTXML_NAME --from-file=$CONFIGMAP_TESTXML_FILE -n $NAMESPACE
else
	~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf create configmap $CONFIGMAP_TESTXML_NAME --from-file=$CONFIGMAP_TESTXML_FILE -n $NAMESPACE
fi


if [ -n "$(~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf get job -n $NAMESPACE | grep $JOB_NAME)" ];then
        ~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf delete job -n $NAMESPACE $JOB_NAME
        ~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf apply -f $YAML_FILE
else
        ~/kubectl --kubeconfig ~/{{ cluster_name }}/admin.conf apply -f $YAML_FILE
fi
